package repositories

import (
	"myblog/models"
	
	"gorm.io/gorm"
)

type ArticleRepository struct {
	db *gorm.DB
}

func NewArticleRepository(db *gorm.DB) *ArticleRepository {
	return &ArticleRepository{db: db}
}

func (r *ArticleRepository) Create(article *models.Article) error {
	return r.db.Create(article).Error
}

func (r *ArticleRepository) GetBySlug(slug string) (*models.Article, error) {
	var article models.Article
	err := r.db.Where("slug = ?", slug).First(&article).Error
	return &article, err
}

func (r *ArticleRepository) GetAllPublished() ([]models.Article, error) {
	var articles []models.Article
	err := r.db.Where("published = ?", true).Order("created_at DESC").Find(&articles).Error
	return articles, err
}

func (r *ArticleRepository) GetAll() ([]models.Article, error) {
	var articles []models.Article
	err := r.db.Order("created_at DESC").Find(&articles).Error
	return articles, err
}

func (r *ArticleRepository) Update(article *models.Article) error {
	return r.db.Save(article).Error
}

func (r *ArticleRepository) Delete(id uint) error {
	return r.db.Delete(&models.Article{}, id).Error
}

func (r *ArticleRepository) FindByID(id uint) (*models.Article, error) {
	var article models.Article
	err := r.db.First(&article, id).Error
	return &article, err
}